package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GunzipInputStream {
	public static final int BUFFER = 4096;

	public static void gunzip(InputStream is, OutputStream os)
			throws IOException {

		GZIPInputStream gis = null;
		try {
			gis = new GZIPInputStream(is);
			int count = 0;
			byte data[] = new byte[BUFFER];
			while ((count = gis.read(data, 0, BUFFER)) != -1) {
				os.write(data, 0, count);
			}

		} finally {
			closeQuietly(gis);
		}

	}

	public static byte[] gunzip(byte[] bytes) throws IOException {

		ByteArrayOutputStream baOut = null;
		ByteArrayInputStream baIn = null;
		GZIPInputStream gzIn = null;
		try {
			baOut = new ByteArrayOutputStream();
			baIn = new ByteArrayInputStream(bytes);
			gzIn = new GZIPInputStream(baIn);
			int count = 0;
			byte data[] = new byte[BUFFER];
			while ((count = gzIn.read(data, 0, BUFFER)) != -1) {
				baOut.write(data, 0, count);
			}

			return baOut.toByteArray();
		} finally {
			closeQuietly(gzIn);
			closeQuietly(baIn);
			closeQuietly(baOut);
		}
	}

	public static void closeQuietly(Closeable stream) {
		if (stream != null) {
			try {
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
